﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using kwzx.Data;
using kwzx.Common;
using System.IO;
using System.Threading;

namespace kwzx
{

    public partial class frmScmDataSyns : Form
    {
        public frmScmDataSyns()
        {
            InitializeComponent();
        }


        DataSet1TableAdapters.T_BMTableAdapter bm = new DataSet1TableAdapters.T_BMTableAdapter();
        DataSet1TableAdapters.T_GROUPTableAdapter group = new DataSet1TableAdapters.T_GROUPTableAdapter();
        DataSet1TableAdapters.V_jg_bmTableAdapter vjgbm = new DataSet1TableAdapters.V_jg_bmTableAdapter();



        private void frmScmDataSyn_Load(object sender, EventArgs e)
        {
            InitTree();
            this.dataGridView1.RowHeadersVisible = false;
            dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
        }

        private void SetTextMessage(int ipos)
        {
            this.Invoke((MethodInvoker)delegate
            {
                this.labProgress.Text = ipos.ToString() + "/100";
                this.progressBar1.Value = Convert.ToInt32(ipos);
                if (ipos == 100)
                {
                    this.labProgress.Text = "导入完成";
                }
            });
        }



        private void btnSynDept_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                int deptID = int.Parse(treeView1.SelectedNode.Tag.ToString());//部门ID
                int DEPT_id = -1;
                string DeptType = treeView1.SelectedNode.ToolTipText;
                if (DeptType == "jg")
                {

                    using (HXYKTEntities db1 = new HXYKTEntities())
                    {
                        var model = db1.T_BM.Where(a => a.GRPUP_ID == deptID).FirstOrDefault();
                        if (model != null)
                        {
                            DEPT_id = model.DEPT_id;
                        }
                    }
                }
                else
                {
                    DEPT_id = deptID;
                }
                new Thread(new ThreadStart(delegate
                {
                    HXYKTEntities db = new HXYKTEntities();
                    var bm = db.T_BM.ToList().Where(a => a.DEPT_id == DEPT_id);
                    int id = 1;

                    try
                    {
                        foreach (var item in bm.ToList())
                        {
                            int ipos = 100 * id / bm.ToArray().Length;

                            SetTextMessage(ipos);
                            id++;
                            CallProc call = new CallProc();
                            if (item.GRPUP_ID != 83)
                            {
                                call.DeptEx(item.DEPT_id.ToString(), 1001, item.BMMC.ToString(), false);
                            }
                            else
                            {
                                if (item.SJBM == 0)
                                {
                                    call.DeptEx(item.DEPT_id.ToString(), int.Parse(item.GRPUP_ID.ToString()), item.BMMC.ToString(), true);
                                }
                                else
                                {
                                    call.DeptEx(item.DEPT_id.ToString(), int.Parse(item.SJBM.ToString()), item.BMMC.ToString(), true);
                                }

                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        string log = string.Format("同步部门失败,请联系软件维护人员");
                        this.rtFailInfo.Text += log + ex.ToString();
                        Log.WriteInfo(log);

                    }

                    rtFailInfo.Invoke(new Action(() =>
                    {
                        rtFailInfo.Text = "同步部门信息成功";
                    }));


                })).Start();

            }

        }

        private void btnSynPerson_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode.Nodes != null)
            {
                HXYKTEntities db = new HXYKTEntities();
                DataGridView DataGridView2 = new DataGridView();
                List<View_UserInfo> user = new List<View_UserInfo>();
                int girdcount = Convert.ToInt32(this.dataGridView1.Rows.Count.ToString());
                for (int i = 0; i < girdcount; i++)
                {
                    //如果DataGridView是可编辑的，将数据提交，否则处于编辑状态的行无法取到  
                    dataGridView1.EndEdit();
                    DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells["cb_check"];
                    Boolean flag = Convert.ToBoolean(checkCell.Value);
                    if (flag == true)     //查找被选择的数据行  
                    {
                        //从 DATAGRIDVIEW 中获取数据项  
                        int z_zcode = int.Parse(dataGridView1.Rows[i].Cells[0].Value.ToString().Trim());

                        user.Add(db.View_UserInfo.Where(a => a.user_id == z_zcode).FirstOrDefault());

                    }
                }
                int groupID = int.Parse(treeView1.SelectedNode.Tag.ToString());
                string nodeType = treeView1.SelectedNode.ToolTipText;
                string name = treeView1.SelectedNode.Text;
                this.rtFailInfo.Text = "";
                if (nodeType == "jg")
                {

                    if (groupID == -1)
                    {
                        this.rtFailInfo.Text = "正在同步" + name + "所有部门下人员信息" + Environment.NewLine;
                    }
                    else if (groupID == 0)
                    {
                        this.rtFailInfo.Text = "正在同步" + name + "所有部门下人员信息" + Environment.NewLine;
                    }
                    else
                    {
                        this.rtFailInfo.Text = "正在同步" + name + "下人员信息" + Environment.NewLine;
                    }
                }
                if (nodeType == "bm")
                {
                    this.rtFailInfo.Text = "正在同步" + name + "下人员信息" + Environment.NewLine;
                }

                new Thread(new ThreadStart(delegate
               {

                   int count = user.Count();
                   DBHelperEX dbHelper = new DBHelperEX();
                   int id = 1;
                   int failID = 0;
                   foreach (var item in user)
                   {
                       SetTextMessage(100 * id / count);
                       id++;
                       string sex = item.XB == null ? "男" : item.XB;
                       string photoPath = item.ZP == null ? "" : item.ZP;
                       if (photoPath == "" || !item.ZP.ToString().Contains("ftp"))
                       {
                           failID++;
                           rtFailInfo.Invoke(new Action(() =>
                           {
                               rtFailInfo.Text += "姓名" + item.ZSXM + "无相片路径不予同步" + Environment.NewLine;

                           }));
                           continue;

                       }
                       var userCount = user.Where(a => a.rybh == item.rybh).ToArray();
                       if (userCount.Length > 1)
                       {
                           failID++;
                           rtFailInfo.Invoke(new Action(() =>
                           {
                               rtFailInfo.Text += "姓名：" + item.ZSXM + "人员编号:" + item.rybh.ToString() + "重复个数" + userCount.Length + Environment.NewLine;

                           }));
                       }
                       int supNum = photoPath.LastIndexOf("ftp") + 4;  //最后一个出现 在加上ftp/
                       photoPath = photoPath.Substring(supNum, photoPath.Length - supNum);
                       int userImginfo = photoPath.IndexOf("/") + 1;
                       string imgName = photoPath.Substring(userImginfo, photoPath.Length - userImginfo);
                       string kkzp = FileTran.DownloadFile(SPicUtils.path, imgName, photoPath);
                       string platName = SPicUtils.path + imgName;
                       string photoName = "";
                       CallProc call = new CallProc();
                       if (File.Exists(platName))//
                       {
                           scm_mainEntities scm = new scm_mainEntities();
                           string scmDepid = item.DEPT_id.ToString();
                           var deptModel = scm.dt_dep.Where(a => a.dep_no_add == scmDepid).FirstOrDefault();
                           if (deptModel == null)
                           {
                               var yktDept = db.T_BM.Where(a => a.DEPT_id == item.DEPT_id).FirstOrDefault();
                               if (yktDept.GRPUP_ID != 83)
                               {
                                   call.DeptEx(yktDept.DEPT_id.ToString(), 1001, yktDept.BMMC.ToString(), false);
                               }
                               else
                               {
                                   if (yktDept.SJBM == 0)
                                   {
                                       call.DeptEx(yktDept.DEPT_id.ToString(), int.Parse(yktDept.GRPUP_ID.ToString()), yktDept.BMMC.ToString(), true);
                                   }
                                   else
                                   {
                                       call.DeptEx(yktDept.DEPT_id.ToString(), int.Parse(yktDept.SJBM.ToString()), yktDept.BMMC.ToString(), true);
                                   }

                               }
                           }
                           photoName = call.UserEx(item.rybh.ToString(), item.ZSXM.ToString(), 1, sex, item.sfzh.ToString(), 0, item.DEPT_id.ToString());
                           if (!string.IsNullOrWhiteSpace(photoName))
                           {
                               //scm平台照片存放文件夹命名方式为人员序号除以1000
                               int folderName = int.Parse(photoName.Substring(0, photoName.Length - 4)) / 1000;
                               if (!Directory.Exists(SPicUtils.path + folderName))
                               {
                                   Directory.CreateDirectory(SPicUtils.path + folderName);
                               }
                               string scmphotoName = SPicUtils.path + folderName + "\\" + photoName;
                               string tmpImgPath = AppDomain.CurrentDomain.BaseDirectory + imgName;  //用于存放临时图片
                               //裁减图片原图片为平台原始图片,保存在scm平台根目录,因后面要压缩 故没有放在对应文件夹中
                               imgUtils.CutForCustom(SPicUtils.path + imgName, tmpImgPath, 140, 194, 0);
                               //压缩图片  原图片在scm平台图片根目录,压缩后图片在人员序号/1000的文件夹中，长,宽，质量
                               Common.CommonImg.CompressImage(tmpImgPath, scmphotoName, 194, 140, 60);
                               //imgUtils.GetReducedImage(exportPath + imgName, scmphotoName, 140, 194, 0);

                               //删除根目录图片
                               File.Delete(tmpImgPath);
                               FileInfo scmphoto = new FileInfo(scmphotoName);
                               FileTran.SaveFile(scmphoto, photoName, folderName.ToString() + "/", 10086);
                           }
                           else
                           {

                           }
                       }
                       else
                       {
                           failID++;
                           this.Invoke((MethodInvoker)delegate
                           {
                               if (item.rybh != null && item.sfzh != null)
                               {
                                   //照片不存在进行同步
                                   photoName = call.UserEx(item.rybh.ToString(), item.ZSXM.ToString(), 0, sex, item.sfzh.ToString(), 0, item.DEPT_id.ToString());


                                   string log = string.Format("姓名:{0}身份证{1}无照片或者照片不匹配照片名:{2}" + Environment.NewLine, item.ZSXM, item.sfzh, imgName);
                                   this.rtFailInfo.Text += log + Environment.NewLine; ;
                                   Log.WriteInfo(log);

                               }
                               else
                               {

                                   this.rtFailInfo.Text += item.ZSXM + "无人员编号" + Environment.NewLine; ;

                               }
                           });
                       }

                   }
                   rtFailInfo.Invoke(new Action(() =>
                   {
                       rtFailInfo.Text += "同步" + name + "下人员信息成功" + Environment.NewLine;
                       rtFailInfo.Text += "共" + count + "条信息,其中同步成功" + (count - failID) + "条信息" + Environment.NewLine;
                   }));
               }

                 )).Start();
            }
        }




        private void InitTree()
        {
            DataTable group_tb = group.GetDataBy_sjjg(0);
            for (int g = 0; g < group_tb.Rows.Count; g++)
            {
                TreeNode tn = new TreeNode();
                tn = treeView1.Nodes.Add(group_tb.Rows[g]["JGNAME"].ToString());
                tn.Text = group_tb.Rows[g]["jc"].ToString();
                tn.Tag = -1;
                tn.ToolTipText = "jg";
                tn.ImageIndex = 0;
                tn.SelectedImageIndex = 0;
                //  tn.Checked = true;
                //addJGTree(tn.Tag.ToString(), tn);
                addBMTree(group_tb.Rows[g]["GRPUP_ID"].ToString(), "0", tn);
            }
            //外协单位
            TreeNode tn1 = new TreeNode();
            tn1 = treeView1.Nodes.Add("外协单位");
            tn1.Text = "外协单位";
            tn1.Tag = "0";
            tn1.ToolTipText = "jg";
            tn1.ImageIndex = 0;
            tn1.SelectedImageIndex = 0;
            tn1.Checked = true;
            addJGTree(group_tb.Rows[0]["GRPUP_ID"].ToString(), tn1);
            //  treeView1.Nodes[0].ExpandAll();
            //   treeView1.SelectedNode = treeView1.Nodes[0].NextVisibleNode;
        }



        /// <summary>
        /// 递归加载addJGTree列表
        /// </summary>
        /// <param name="fatherid">节点的fatherid</param>
        /// <param name="pnode">该节点</param>
        private void addJGTree(string fatherid, TreeNode pnode)
        {
            DataTable dt = group.GetDataBy_sjjg(int.Parse(fatherid));
            DataView dvTree = new DataView(dt);
            dvTree.RowFilter = "[SJJG] = " + fatherid;
            foreach (DataRowView drv in dvTree)
            {
                TreeNode node = new TreeNode();
                node.ImageIndex = 1;
                node.SelectedImageIndex = 3;
                if (pnode == null)
                {
                    node.Text = drv["jc"].ToString();
                    node.Tag = drv["GRPUP_ID"].ToString();    //作为节点标识符
                    node.ToolTipText = "jg";
                    treeView1.Nodes.Add(node);
                    addJGTree(drv["GRPUP_ID"].ToString(), node);//递归  该节点加载子节点
                }
                else
                {
                    node.Text = drv["jc"].ToString();
                    node.Tag = drv["GRPUP_ID"].ToString();//作为节点标识符
                    node.ToolTipText = "jg";
                    pnode.Nodes.Add(node);
                    addJGTree(drv["GRPUP_ID"].ToString(), node);//递归  该节点加载子节点

                }
            }
        }

        /// <summary>
        /// 递归加载addBMTree列表
        /// </summary>
        /// <param name="fatherid">节点的fatherid</param>
        /// <param name="pnode">该节点</param>
        private void addBMTree(string jgid, string fatherid, TreeNode pnode)
        {
            DataTable dt = bm.GetDataBy_grpup_id(int.Parse(jgid));
            DataView dvTree = new DataView(dt);
            dvTree.RowFilter = "[SJBM] = " + fatherid;
            foreach (DataRowView drv in dvTree)
            {
                TreeNode node = new TreeNode();
                node.ImageIndex = 1;
                node.SelectedImageIndex = 3;
                if (pnode == null)
                {
                    node.Text = drv["BMMC"].ToString();
                    node.Tag = drv["DEPT_ID"].ToString();    //作为节点标识符
                    node.ToolTipText = "bm";
                    treeView1.Nodes.Add(node);
                    addBMTree(jgid, drv["DEPT_ID"].ToString(), node);//递归  该节点加载子节点
                }
                else
                {
                    node.Text = drv["BMMC"].ToString();
                    node.Tag = drv["DEPT_ID"].ToString();//作为节点标识符
                    node.ToolTipText = "bm";
                    pnode.Nodes.Add(node);
                    addBMTree(jgid, drv["DEPT_ID"].ToString(), node);//递归  该节点加载子节点
                }
            }
        }


        private List<View_UserInfo> user;
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                int deptID = int.Parse(treeView1.SelectedNode.Tag.ToString());//部门ID
                string DEPT_id = "-1";
                string DeptType = treeView1.SelectedNode.ToolTipText;
                if (DeptType == "jg")
                {

                    using (HXYKTEntities db1 = new HXYKTEntities())
                    {
                        var model = db1.T_BM.Where(a => a.GRPUP_ID == deptID).FirstOrDefault();
                        if (model != null)
                        {
                            DEPT_id = model.DEPT_id.ToString();
                        }
                    }
                }
                else
                {
                    DEPT_id = deptID.ToString();
                }
                this.labSynPerson.Text = e.Node.Text;
                rtFailInfo.Text = "";
                HXYKTEntities db = new HXYKTEntities();
                scm_mainEntities scm = new scm_mainEntities();
                CallProc call = new CallProc();
                //一卡通 人员在scm 平台查找 如果有 说明是新增

                List<dt_user> listScmUser = scm.dt_user.Where(a => a.dep_no_add == DEPT_id).ToList();
                int yktDeptid = int.Parse(DEPT_id);
                List<View_UserInfo> viewuser = db.View_UserInfo.Where(a => a.ZP.Contains("ftp")).Where(a => a.DEPT_id == yktDeptid).OrderBy(c => c.XM).ToList();
                foreach (var item in listScmUser)
                {
                    var lackuser = viewuser.Where(a => a.rybh == item.user_no).FirstOrDefault();
                    if (lackuser != null)
                    {
                        viewuser.Remove(lackuser);
                    }
                }


                this.rtFailInfo.Text = "此次可以同步的数据为" + viewuser.Count().ToString() + "条";

                this.dataGridView1.DataSource = viewuser;
                if (viewuser.Count > 0)
                {
                    this.btnSynPerson.Enabled = true;
                    user = viewuser;
                }
            }
        }

        //实现全选全不选
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                if (dataGridView1.Rows.Count > 0)
                {
                    for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    {
                        dataGridView1.Rows[i].Cells[1].Value = true;
                    }
                }
            }
            else
            {
                if (dataGridView1.Rows.Count > 0)
                {
                    for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    {
                        if ((bool)dataGridView1.Rows[i].Cells[1].EditedFormattedValue)
                        {
                            dataGridView1.Rows[i].Cells[1].Value = false;
                        }
                        else
                        {
                            dataGridView1.Rows[i].Cells[0].Value = true;
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 查询人员信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {

            List<View_UserInfo> viewuser = (List<View_UserInfo>)this.dataGridView1.DataSource;
            List<View_UserInfo> view = viewuser;
            if (this.txtRybh.Text.ToString() != "")
            {
                view = viewuser.Where(c => c.rybh.Contains(txtRybh.Text)).ToList();
            }
            if (this.txtUserName.Text.ToString() != "")
            {
                view = viewuser.Where(c => c.XM.Contains(txtUserName.Text)).ToList();
            }


            this.dataGridView1.DataSource = view;




        }














    }
}
